import {Image, View} from "@tarojs/components";
import {Component} from "react";
import {createClassFun, CUSTOM_SCHOOL_LOGO_IDS} from "../utils";
import loginBackGroundImage from "../images/login-back.png"
import "./index.scss"
import {InputComponent} from "../inputComponent";
import loginSchoolIcon from "../images/login-school-icon.png"
import loginUserIcon from "../images/login-user.png"
import loginPasswordIcon from "../images/login-password.png"
import LgButton from "../../components/button";
import Taro from "@tarojs/taro"
import {LoginResult, LoginResultState, OnShowAppParams, SchoolSimpleInfo} from "../types";
import {getSchoolSimpleInfoList, loginByUserNameAndPassword} from "../api";
import {Toast} from "../toast";
import {md5Utils} from "../md5";
import {getStorage} from "../../components/utils";


const storage = getStorage();

const {classNames, rootClass} = createClassFun("weapp-login-component")

export interface LoginComponentProps {
   appId: string
   loginIcon: string
   systemName: string
   systemId: string
   showRegisterBtn?: boolean
  showForgetPassword?: boolean
  showVisitorBtn?: boolean
   registerPath?: string

   onLoginSuccess?(loginResult: LoginResult): void
}

export interface LoginComponentState {
   lockSchoolChosen:boolean
   currentSchoolId: string
   currentSchoolVersion: string
   currentSchoolItem:SchoolSimpleInfo | object
   searchSchoolName: string
   userName: string
   password: string
   schoolShowList: SchoolSimpleInfo[]
}

export class LoginComponent extends Component<LoginComponentProps, LoginComponentState> {

   private currentSchoolId: string
   private schoolList: SchoolSimpleInfo[]

   constructor(props) {
      super(props);
      this.currentSchoolId = ""
      this.schoolList = []
      this.state = {
         lockSchoolChosen:false,
         currentSchoolId: '',
         currentSchoolVersion: '2.0',
         currentSchoolItem: {},
         searchSchoolName: "",
         userName: "",
         password: "",
         schoolShowList: []
      }
   }

   async loadSchoolInfo() {
      try {
         const schoolSimpleInfos = await getSchoolSimpleInfoList();
         let currentSchoolInfo: any = storage.get("currentSchoolInfo")
         currentSchoolInfo = currentSchoolInfo ? JSON.parse(currentSchoolInfo) : ''
         let searchSchoolName = this.state.searchSchoolName;
         let currentSchoolId = this.state.currentSchoolId
         let currentSchoolVersion = this.state.currentSchoolVersion
         let currentSchoolItem = this.state.currentSchoolItem
         if (currentSchoolInfo) {
            this.currentSchoolId = currentSchoolInfo.schoolId
            currentSchoolId = currentSchoolInfo.schoolId
            currentSchoolVersion = currentSchoolInfo.version
            currentSchoolItem = currentSchoolInfo
            searchSchoolName = currentSchoolInfo.schoolName
         }
         this.schoolList = schoolSimpleInfos
         this.setState({
            currentSchoolId,
            currentSchoolVersion,
            currentSchoolItem,
            searchSchoolName,
         })
      } catch {
         await Toast.error("获取学校数据失败")
      }
   }

   checkLockSchoolChosen():boolean{//扫码 || 非退出情况下重新登录 || lockId
      const currentSchoolInfo = JSON.parse(storage.get('currentIdentityInfo') || '{}')
      const app = Taro.getApp().$app
      const schoolId = currentSchoolInfo.schoolID// S-XHWLXX
      const isLogOut = app.isUserLogout
      return !isLogOut && !!CUSTOM_SCHOOL_LOGO_IDS.find(item => item === schoolId)
   }

   async checkIsLockSchoolChoose(){
      const app = Taro.getApp().$app
      if(app.isUserLogout) {
         this.setState({ lockSchoolChosen:false })
      }else{
         const onShowOptionsSync = await Taro.getEnterOptionsSync()//报错但能正常使用
         const store:any = JSON.parse(storage.get('onShowOptionsSyncInfo') || '{}')
         let query = onShowOptionsSync.query || store.query as OnShowAppParams// {"lockSchoolId":"S-XHWLXX"} 优先级扫码>缓存

         const lockSchoolId = query.lockSchoolId || ''
         const schoolList = this.schoolList
         let currentSchoolInfo
         if(lockSchoolId){
            currentSchoolInfo = schoolList.find(item => item.schoolId === lockSchoolId) as SchoolSimpleInfo
         }else{
            currentSchoolInfo = JSON.parse(storage.get('currentIdentityInfo') || '{}')
         }
         const lockSchoolChosen = lockSchoolId || this.checkLockSchoolChosen()
         if(lockSchoolChosen){
            this.setState({ lockSchoolChosen: lockSchoolChosen, currentSchoolItem:currentSchoolInfo })
            this.selectSchool(lockSchoolId, currentSchoolInfo)
         }
      }
   }

   async componentDidMount() {
      await this.loadSchoolInfo()
      await this.checkIsLockSchoolChoose()
   }

   updateSchoolShowList() {
      this.currentSchoolId = ""
      if (this.state.searchSchoolName) {
         this.setState({
            schoolShowList: this.schoolList.filter(item => {
               const schoolName = item.schoolName
               if (this.state.searchSchoolName.indexOf('LG') != -1) {//包含LG
                  return schoolName.indexOf('LG') != -1 && schoolName.indexOf(this.state.searchSchoolName) != -1
               } else {
                  return schoolName.indexOf('LG') == -1 && schoolName.indexOf(this.state.searchSchoolName) != -1
               }
            })
         })
      } else if (this.state.schoolShowList.length) {
         this.setState({
            schoolShowList: []
         })
      }
   }


   render() {
      const currentSchoolItem = this.state.currentSchoolItem as SchoolSimpleInfo
      const lockSchoolChosen = this.state.lockSchoolChosen
      const schoolLogo = lockSchoolChosen ? (currentSchoolItem.schoolLogoUrl || this.props.loginIcon) : this.props.loginIcon
      const schoolName = lockSchoolChosen ? currentSchoolItem.schoolName : this.props.systemName
      return (
         <View className={rootClass("")}>
            <View className={classNames("header")}>
               <Image mode="aspectFill" src={loginBackGroundImage} className={classNames("background")}/>
               <View className={classNames("info")}>
                  <Image mode="aspectFill" src={schoolLogo} className={classNames("login-icon")}/>
                  <View className={classNames("system-name")}>{schoolName}</View>
               </View>
            </View>
            <View className={classNames("body")}>
               <View className={classNames("form")}>
                  <View className={classNames("input-item")}>
                     {
                        lockSchoolChosen ? null : (
                           <InputComponent onFocus={() => this.searchInputFocus()}
                                           onInput={value => this.setState({
                                              searchSchoolName: value,
                                              currentSchoolId: ''
                                           }, () => this.updateSchoolShowList())}
                                           className={classNames("school-search-input")} value={this.state.searchSchoolName}
                                           icon={loginSchoolIcon} placeholder="请输入名称搜索学校...">
                              {
                                 !this.state.schoolShowList.length ? "" :
                                    <View className={classNames("school-list")}>
                                       {
                                          this.state.schoolShowList.map(item => (
                                             <View onClick={() => this.selectSchool(item.schoolId, item)}
                                                   key={item.id}
                                                   className={classNames("school-list-item")}>
                                                {
                                                   item.schoolName
                                                }
                                             </View>
                                          ))
                                       }
                                    </View>
                              }
                           </InputComponent>
                        )
                     }
                     <InputComponent value={this.state.userName} onInput={value => this.setState({userName: value})}
                                     icon={loginUserIcon} placeholder="请输入帐号..."/>
                     <InputComponent password={true} value={this.state.password}
                                     onInput={value => this.setState({password: value})} icon={loginPasswordIcon}
                                     placeholder="请输入密码..."/>
                  </View>
                  <View className={classNames("btn-area")}>
                     <LgButton onClick={() => this.login()} type="B" className={classNames("login-btn")}>登录</LgButton>
                  </View>
                  {
                     this.state.currentSchoolId && this.state.currentSchoolVersion !== '1.0' ? (
                        <View className={classNames("hand-area")}>
                          {
                            this.props.showForgetPassword ? (
                              <View className={(classNames("hand-area-item"))} onClick={() => {
                                this.goToForgetPwd()
                              }}>忘记密码？</View>
                            ) : null
                          }
                          {/*{*/}
                          {/*  this.props.showVisitorBtn ? (*/}
                          {/*    <View className={(classNames("hand-area-item"))} onClick={() => {*/}
                          {/*      this.goToVisitor()*/}
                          {/*    }}>游客访问</View>*/}
                          {/*  ) : null*/}
                          {/*}*/}
                        </View>
                     ) : null
                  }
               </View>
            </View>
            <View className={classNames("footer")}>
               {
                  this.props.showRegisterBtn && this.state.currentSchoolId && this.state.currentSchoolVersion !== '1.0' ?
                     <View className={classNames("register-tips")}>
                        还没有帐号？点击<View onClick={() => this.gotoRegister()}
                                      className={classNames("register-btn")}>注册帐号</View>
                     </View> : null
               }
            </View>
         </View>
      )
   }

   private gotoRegister() {
      if (!this.props.registerPath) {
         return
      }
      Taro.navigateTo({
         url: this.props.registerPath
      }).then()
   }

   private goToForgetPwd() {
      Taro.navigateTo({
         url: '/pages/forgetPassword/index'
      }).then()
   }


   // async goToVisitor() {
   //    let currentSchoolInfoStr = storage.get('currentSchoolInfo')
   //    if (!currentSchoolInfoStr) {
   //       throw new Error('请选择学校')
   //    }
   //    const currentSchoolInfo: SchoolSimpleInfo = JSON.parse(currentSchoolInfoStr)
   //    try {
   //       const {hostServerUrl, schoolId} = currentSchoolInfo
   //       if (!hostServerUrl || !schoolId) {
   //          throw new Error('请选择学校')
   //       }
   //       Toast.showLoading('请稍后')
   //       const data = await checkPortalExist(hostServerUrl, schoolId)
   //       Toast.hideLoading()
   //       if (data.data) {
   //          storage.set('portalUrl', data.data)
   //          storage.set('firstChoseType', 'visitor')
   //          Taro.navigateTo({
   //             url: '/pages/campusPortal/pages/home/index'
   //          })
   //       } else {//空地址
   //          this.navigateToNoPortalHomePage()
   //       }
   //    } catch (err) {
   //       Toast.hideLoading()
   //       this.navigateToNoPortalHomePage()
   //    }
   // }

   // navigateToNoPortalHomePage() {
   //    storage.set('firstChoseType', 'visitor')
   //    app.globalData.userName = "游客";
   //    app.globalData.userID = "";
   //    Taro.navigateTo({
   //       url: '/pages/campusPortal/pages/home/index'
   //    })
   // }

   private selectSchool(schoolId: string, item: SchoolSimpleInfo) {
      this.currentSchoolId = schoolId
      storage.set('currentSchoolInfo', JSON.stringify(item))
      this.setState({
         currentSchoolId: schoolId,
         currentSchoolVersion: item.version,
         currentSchoolItem: item,
         searchSchoolName: item.schoolName,
         schoolShowList: []
      })
   }

   private async login() {
      const searchSchoolName = this.state.searchSchoolName.trim();
      if (!searchSchoolName) {
         await Toast.error("请输入学校名称")
         return
      }

      let currentSchoolId = this.currentSchoolId;
      if (!currentSchoolId) {
         const schoolInfo = this.schoolList.find(item => item.schoolName === this.state.searchSchoolName)
         if (!schoolInfo) {
            await Toast.error("该学校不存在")
            return
         }
         currentSchoolId = schoolInfo.schoolId
      }

      const userName = this.state.userName.trim();
      if (!userName) {
         await Toast.error("请输入帐号")
         return
      }

      const password = this.state.password.trim();
      if (!password) {
         await Toast.error("请输入密码")
         return
      }

      try {
         await Toast.showLoading("请稍后")
         const successCallbackResult = await Taro.login();
         const loginResult = await loginByUserNameAndPassword({
            AppID: this.props.appId,
            PSW: md5Utils.reverseMD5String(password),
            SchoolID: currentSchoolId,
            SysTemID: this.props.systemId,
            UserID: userName,
            js_Code: successCallbackResult.code
         });
         Toast.hideLoading()
         switch (loginResult.state) {
            case LoginResultState.SUCCESS:
               this.props.onLoginSuccess && this.props.onLoginSuccess(loginResult);
               break;
            case LoginResultState.UNBIND:
               break;
            case LoginResultState.LOGIN_YUN_FAIL:
               await Toast.error(loginResult.msg || "登录失败，请稍候再试");
               break;
            case LoginResultState.LOGIN_WX_FAIL:
               break;////获取微信信息失败，一般是获取UinonID失败
            case LoginResultState.LOGIN_ERROR_SCHOOL_ID:
               await Toast.error('获取学校信息失败,请重新登录');
               break;
            case LoginResultState.OTHER_FAIL:
               await Toast.error("登录失败，请稍候再试");
               break;
         }
      } catch (e) {
         Toast.hideLoading()
         await Toast.error(e instanceof Error && e.message ? e.message : "登录失败")
      }
   }

   private searchInputFocus() {
      this.updateSchoolShowList()
   }
}
